#!/usr/bin/env bash
set -e

################## 可自定义变量 ##################
WORKDIR=/opt/proxy
# 使用命令行参数或默认值
PORT=${1:-3128}        # 如果未传入参数1，默认3128
USER=${2:-username}          # 如果未传入参数2，默认sy
PASS=${3:-password}         # 如果未传入参数3，默认lyz
IMAGE=swr.cn-east-2.myhuaweicloud.com/suyuansoft/hub:squid-5.2
TIMEZONE=Asia/Shanghai        # ====== 关键行 ======
###################################################

echo "==> 使用配置："
echo "    PORT: $PORT"
echo "    USER: $USER"
echo "    PASS: $PASS"
echo "    TIMEZONE: $TIMEZONE"

echo "==> 1. 设置宿主机时区为 $TIMEZONE"
if command -v timedatectl &>/dev/null; then
    sudo timedatectl set-timezone "$TIMEZONE"
else
    sudo ln -sf "/usr/share/zoneinfo/$TIMEZONE" /etc/localtime
    echo "$TIMEZONE" | sudo tee /etc/timezone
fi

echo "==> 2. 创建工作目录 $WORKDIR"
sudo mkdir -p "$WORKDIR" && cd "$WORKDIR"

echo "==> 3. 生成密码文件"
docker run --rm swr.cn-east-2.myhuaweicloud.com/suyuansoft/hub:httpd-2.4 htpasswd -nbB "$USER" "$PASS" | sudo tee passwd >/dev/null

echo "==> 4. 写 squid.conf"
cat <<EOF | sudo tee squid.conf >/dev/null
http_port 0.0.0.0:${PORT}
auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwd
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
http_access deny all
EOF

echo "==> 5. 生成 docker-compose.yml (绑定时区 & 环境变量)"
cat <<EOF | sudo tee docker-compose.yml >/dev/null
version: '2.2'
services:
  squid:
    image: ${IMAGE}
    restart: unless-stopped
    environment:
      - TZ=${TIMEZONE}
    ports:
      - "${PORT}:${PORT}"
    volumes:
      - ./squid.conf:/etc/squid/squid.conf:ro
      - ./passwd:/etc/squid/passwd:ro
      - /etc/localtime:/etc/localtime:ro      # 时区同步
EOF

echo "==> 6. 启动容器"
sudo docker-compose up -d

echo "======================================================"
echo "Proxy 已就绪："
echo "  地址:  $(curl -s http://ip.3322.net):${PORT}"
echo "  用户:  ${USER}"
echo "  密码:  ${PASS}"
echo "  时区:  ${TIMEZONE}"
echo "======================================================"